package com.tanhua.server.interceptor;

import com.tanhua.common.mapper.ActiveStartMapper;
import com.tanhua.common.pojo.ActiveStart;
import com.tanhua.common.pojo.User;
import com.tanhua.common.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 记录活跃时间
 */
@Component
public class ActiveTime implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ActiveStartMapper activeStartMapper;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        User user = UserThreadLocal.get();
        if(null==user){
            return true;
        }
        String HuoYue = redisTemplate.opsForValue().get("HuoYue" + user.getId());//开始使用时间
        if (HuoYue != null) {
            Long HuoYue2 = Long.valueOf(HuoYue);
            Integer aLong = Integer.valueOf(redisTemplate.opsForValue().get("HuoYuestart" + user.getId()));//修改时间用的id
            long now = System.currentTimeMillis();
            long HuoYuenow = now - HuoYue2;
            if (HuoYuenow > 60 * 10 * 1000) {
                ActiveStart activeStart = new ActiveStart();
                activeStart.setId(aLong);
                Long aLong1 = Long.valueOf(redisTemplate.opsForValue().get("HuoYueover" + user.getId()));//
                if (aLong1 != null) {
                    long l = aLong1 - HuoYue2;
                    activeStart.setLongTime(l);
                }
                redisTemplate.delete("HuoYue" + user.getId());
               activeStart.setUpdated(new Date(aLong1));
               activeStartMapper.updateById(activeStart);
            } else {
                redisTemplate.opsForValue().set("HuoYueover" + user.getId(), String.valueOf(System.currentTimeMillis()));
            }
        } else {
            redisTemplate.opsForValue().set("HuoYue" + user.getId(), String.valueOf(System.currentTimeMillis()));//开始使用时间
            Long increment = redisTemplate.opsForValue().increment("HuoYuestart" + user.getId());//修改时间用的id
            ActiveStart activeStart = new ActiveStart();
            activeStart.setUserId(user.getId());
            activeStart.setCreated(new Date());
            activeStart.setUpdated(new Date());
            activeStartMapper.insert(activeStart);
        }
        return true;
    }
}
